package william.tree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author ZhangShenao
 * @date 2024/1/15
 * @description <a href="https://leetcode.cn/problems/binary-tree-postorder-traversal/description/">...</a>
 */
public class Leetcode145_二叉树的后序遍历 {
    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public List<Integer> postorderTraversal(TreeNode root) {
        //边界条件校验
        if (root == null) {
            return Collections.emptyList();
        }

        List<Integer> result = new ArrayList<>();

        //递归处理
        postorderTraversalRecursive(root, result);

        //返回结果
        return result;
    }

    /**
     * 递归后续遍历
     */
    private void postorderTraversalRecursive(TreeNode root, List<Integer> result) {
        //递归终止条件
        if (root == null) {
            return;
        }

        //首先后续遍历左子树
        postorderTraversalRecursive(root.left, result);

        //然后后续遍历右子树
        postorderTraversalRecursive(root.right, result);

        //最后访问根节点
        result.add(root.val);

    }
}
